package com.qiantu.phone.ui.adapter;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.qiantu.phone.R;
import com.qiantu.phone.app.AppAdapter;

/**
 *    author : Android 轮子哥
 *    github : https://github.com/getActivity/AndroidProject
 *    time   : 2019/09/22
 *    desc   : 状态数据列表
 */
public final class DeviceModeLabelAdapter extends AppAdapter<String> {

    private View lastSelectedView;
    private int lastSelectedPosition = -1;

    public DeviceModeLabelAdapter(@NonNull Context context) {
        super(context);
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ViewHolder();
    }

    private final class ViewHolder extends AppAdapter<?>.ViewHolder {

        private final TextView tvLabel;
        private final ImageView line;

        private ViewHolder() {
            super(R.layout.item_mode);
            tvLabel = findViewById(R.id.tv_label);
            line = findViewById(R.id.line);
        }

        @Override
        public void onBindView(int position) {
            String item = getItem(position);
            tvLabel.setText(item);
            if(lastSelectedPosition == position){
                tvLabel.setSelected(true);
                line.setSelected(true);
                lastSelectedView = itemView;
            }else{
                tvLabel.setSelected(false);
                line.setSelected(false);
            }
        }
    }

    @Override
    public long getItemId(int position) {
        return getData().get(position).hashCode();
    }

    public void selectItem(int position){
        lastSelectedPosition = position;
        DeviceModeLabelAdapter.ViewHolder viewHolder = (ViewHolder) getRecyclerView().findViewHolderForLayoutPosition(position);
        if(viewHolder == null){
            return;
        }
        if(viewHolder.itemView != lastSelectedView){
            viewHolder.tvLabel.setSelected(true);
            viewHolder.line.setSelected(true);
            if(lastSelectedView != null){
                lastSelectedView.findViewById(R.id.tv_label).setSelected(false);
                lastSelectedView.findViewById(R.id.line).setSelected(false);
            }
            lastSelectedView = viewHolder.itemView;
        }
    }
}